<?php
/**
 * Copyright 2011 Facebook, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License. You may obtain
 * a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */

@include(APPPATH.'config/config'.EXT);
require_once $config['external_apis']."/facebook/base_facebook.php";
unset($config);


/**
 * Extends the BaseFacebook class with the intent of using
 * PHP sessions to store user ids and access tokens.
 */
class Facebook extends BaseFacebook
{
  /**
   * Identical to the parent constructor, except that
   * we start a PHP session to store the user ID and
   * access token if during the course of execution
   * we discover them.
   *
   * @param Array $config the application configuration.
   * @see BaseFacebook::__construct in facebook.php
   */
  public function __construct($appID, $secret) {
      $config = array('appId'  => $appID,
                        'secret' => $secret,);
    
    parent::__construct($config);
  }

  protected static $kSupportedKeys =
    array('state', 'code', 'access_token', 'user_id');

  /**
   * Provides the implementations of the inherited abstract
   * methods.  The implementation uses PHP sessions to maintain
   * a store for authorization codes, user ids, CSRF states, and
   * access tokens.
   */
  protected function setPersistentData($key, $value) {
      
    if (!in_array($key, self::$kSupportedKeys)) {
      self::errorLog('Unsupported key passed to setPersistentData.');
      return;
    }

    $session_var_name = $this->constructSessionVariableName($key);
    
    $CI =& get_instance();
    $CI->load->library('session');
    $CI->session->set_userdata($session_var_name);
    unset($CI);
  }

  protected function getPersistentData($key, $default = false) {
    if (!in_array($key, self::$kSupportedKeys)) {
      self::errorLog('Unsupported key passed to getPersistentData.');
      return $default;
    }
    $session_var_name = $this->constructSessionVariableName($key);
    
    $CI =& get_instance();
    $CI->load->library('session');
    $return_value = $CI->session->userdata($session_var_name) ? 
            $CI->session->userdata($session_var_name) : $default;
    unset($CI);
    
    return $return_value;
  }

  protected function clearPersistentData($key) {
    if (!in_array($key, self::$kSupportedKeys)) {
      self::errorLog('Unsupported key passed to clearPersistentData.');
      return;
    }

    $session_var_name = $this->constructSessionVariableName($key);
    
    $CI =& get_instance();
    $CI->load->library('session');
    $CI->session->unset_userdata($session_var_name);
    unset($CI);
  }

  protected function clearAllPersistentData() {
    foreach (self::$kSupportedKeys as $key) {
      $this->clearPersistentData($key);
    }
  }

  protected function constructSessionVariableName($key) {
    return implode('_', array('fb',
                              $this->getAppId(),
                              $key));
  }
  
  // $url: Full URL, Ex: http://www.facebook.com/FanPageURL
  public static function getFanPageJSON($url) {
      // Check Facebook Fan Page link
      
      $segment = explode('/', trim($url,'/'));
      $page_id = $segment[count($segment)-1];

      $fb_graph = self::$DOMAIN_MAP['graph'].$page_id;
      
      $response_string = file_get_contents($fb_graph); 
      
      if (!$response_string || $response_string == '') {
          MessageHandler::add('Cannot get information from the given URL');
          return false;
      }
      
      return $response_string;
    }
    
    public static function getFanPage($url) {
        $str = self::getFanPageJSON($url);
        return ($str && $str != '') ? json_decode($str) : false;
    }
}
